package com.nononsenseapps.feeder.ui.base

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.WindowManager
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.gitee.wsl.common.ui.ext.applicationViewModels
import com.lxj.xpopup.XPopup
import com.nononsenseapps.feeder.db.ARG
import com.nononsenseapps.feeder.ui.R
import com.nononsenseapps.feeder.db.room.AppDatabase
import com.nononsenseapps.feeder.db.entity.FeedItemFeature
import com.nononsenseapps.feeder.model.GlobalViewModel
import com.nononsenseapps.feeder.ui.BuildConfig
import com.nononsenseapps.feeder.ui.FeedNavigationActivity
import com.nononsenseapps.feeder.ui.MutableServerActivity
import com.nononsenseapps.feeder.ui.common.GrayFrameLayout
import com.nononsenseapps.feeder.ui.setting.SettingsViewModel
import com.nononsenseapps.feeder.util.NotificationUtil.cancelNotification
import com.nononsenseapps.feeder.util.PrefUtils
import com.nononsenseapps.feeder.util.isTrue
import kotlinx.coroutines.*
import timber.log.Timber


const val EXPORT_OPML_CODE = 101
const val IMPORT_OPML_CODE = 102
const val EDIT_FEED_CODE = 103

const val EXTRA_FEEDITEMS_TO_MARK_AS_NOTIFIED: String = "items_to_mark_as_notified"
/**
 * A fragment which is also Coroutine aware.
 *
 * All coroutines started in this fragment are linked to the Fragment's lifecycle. If the fragment
 * is destroyed, then all coroutines are cancelled. Likewise, if any of the coroutines encounter
 * an exception, that cancels the other coroutines
 */
@SuppressLint("Registered")
open class CoroutineScopedActivity: AppCompatActivity(){

    protected val database by lazy { AppDatabase.getInstance(this)}

    protected val feedItemDao by lazy { database.feedItemDao() }
    protected val feedDao by lazy { database.feedDao() }
    protected val feedItemFeatureDao by lazy { database.feedItemFeatureDao() }

    protected val featureAdapter by lazy { ArrayAdapter<FeedItemFeature>(this, R.layout.spinner_feature,R.id.feature_title)}

    //protected val globalViewModel by lazy { getGlobalViewModel() }
    //protected val settingsViewModel by lazy { getSettingsViewModel() }

    protected val globalViewModel by applicationViewModels<GlobalViewModel>()
    protected val settingsViewModel by applicationViewModels<SettingsViewModel>()

    protected val handler by lazy {  Handler(Looper.getMainLooper()) }

    protected fun initFeatureAdapter(it: List<FeedItemFeature>) {
        featureAdapter.clear()
        featureAdapter.add(FeedItemFeature(title = getString(R.string.no_feature)))
        featureAdapter.addAll(it)
    }

    override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {
        //debug().isTrue { Timber.d("activity onCreateView  view Name:$name ...") }
        if (PrefUtils.isGrayModel(this)) {
            try {
                if ("FrameLayout" == name) {
                    val count = attrs.attributeCount
                    for (i in 0 until count) {
                        val attributeName = attrs.getAttributeName(i)
                        val attributeValue = attrs.getAttributeValue(i)
                        if (attributeName == "id") {
                            val id = attributeValue.substring(1).toInt()
                            val idVal = resources.getResourceName(id)
                            if ("android:id/content" == idVal) {
                                // grayFrameLayout.setWindow(getWindow());
                                return  GrayFrameLayout(context, attrs)
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return super.onCreateView(name, context, attrs)
    }

    override fun onRestart() {
        super.onRestart()
        debug().isTrue { Timber.d("activity onRestart...") }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        debug().isTrue { Timber.d("activity onCreate...") }
    }

    override fun onResume() {
        super.onResume()
        debug().isTrue { Timber.d("activity onResume...") }
    }

    protected val loadingPop by lazy {
        XPopup.Builder(this).asLoading()
    }


    override fun onDestroy() {
        debug().isTrue { Timber.d("activity onDestroy...") }
        super.onDestroy()
    }

    open fun debug():Boolean = BuildConfig.DEBUG

    protected fun shouldBeFloatingWindow(): Boolean {
        val theme = theme
        val floatingWindowFlag = TypedValue()
        if (theme == null || !theme.resolveAttribute(R.attr.isFloatingWindow, floatingWindowFlag,
                        true)) {
            // isFloatingWindow flag is not defined in theme
            return false
        }
        return floatingWindowFlag.data != 0
    }

    protected fun setupFloatingWindow() {
        // configure this Activity as a floating window, dimming the background
        val params = window.attributes
        params.width = getFloatingWindowWidth()
        params.height = getFloatingWindowHeight()
        params.alpha = 1f
        params.dimAmount = 0.7f
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND
        window.attributes = params
    }

    open fun getFloatingWindowWidth():Int=resources.getDimensionPixelSize(R.dimen.session_details_floating_width)

    open fun getFloatingWindowHeight():Int=resources.getDimensionPixelSize(R.dimen.session_details_floating_height)
}


fun markAsReadAndNotified(context: Context,lifecycleScope:CoroutineScope,id:Long){
    val db = AppDatabase.getInstance(context.applicationContext)

    lifecycleScope.launch(Dispatchers.Default) {
        cancelNotification(context.applicationContext,feedItemId = id)
        delay(1000)
        db.feedItemDao().markAsReadAndNotified(id)
    }
}

fun startFeedNavigation(context: Context,opmlUrl:String="https://raw.githubusercontent.com/wushunlian/app/master/feeder/opml/sample.opml"){
    val intent = Intent(context, FeedNavigationActivity::class.java)
    intent.putExtra(ARG.LINK, opmlUrl)
    context.startActivity(intent)
}

fun startMutableServer(context: Context,addr:String){
    val intent = Intent(context, MutableServerActivity::class.java)
    intent.putExtra(ARG.LINK, addr)
    context.startActivity(intent)
}